package com.thread.threadfirst.studyThread4;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 9、SingleThreadExecutor
 * 顾名思义，线程池中只有一个线程
 * <p>
 * 好处：保证任务执行是有顺序的，先来的先执行。
 */
public class T_ThreadPool3 {
    public static void main(String[] args) {
        ExecutorService service = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 5; i++) {
            final int j = i;
            service.execute(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(j + " " + Thread.currentThread().getName());
            });
        }

        //注意：上面的代码执行完了虚拟机还在开着，要想虚拟机关闭，调用shutdown()就好。
        service.shutdown();
    }
}
